<?php

namespace App\Modules\Apicrzs\Services\Users;

use App\Exceptions\Exception;
use App\Modules\Admin\Entities\Member\UserBankModel;
use App\Modules\Admin\Entities\Member\UserExtractModel;
use App\Modules\Admin\Entities\Member\UserScoreTransactionModel;
use App\Modules\Admin\Entities\Water\GiftScoreModel;
use App\Modules\Admin\Services\BaseService;
use App\Modules\Apicrzs\Entities\ApparatusModel;
use App\Modules\Apicrzs\Entities\UserScoreModel;
use App\Modules\Apicrzs\Entities\UsersModel;
use App\Traits\CryptAES;
use Illuminate\Support\Arr;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;

class UserExtractServices extends BaseService
{
    public function __construct(UserScoreModel $model)
    {
        $token =  \request()->header('token');
        $user_info = CryptAES::decryptToken($token,'user_grzq');

        $this->user_id = $user_info['data']['user_id']??"";
        $this->user_info = $user_info['data'];
        $this->model = $model;
        $this->userScoreModel = new UserScoreModel();
    }
    public function getUserExtractList($params){

        $day_time = date("Y-m-d", strtotime("-1 day"));
        $start_time = strtotime($day_time . ' 00:00:00');

        $where['user_id'] =$this->user_id;
        $where['is_delete'] =0;
        $model = UserExtractModel::getInstance()->where($where);

        $lists = $model->orderBy('created_time', 'DESC')->select(['id','month','extract_price','balance','created_time'])
            ->paginate($this->getLimit($params['limit'] ?? 10));

        return [
            'current_page' => $lists->currentPage(),
            'per_page'     => $lists->perPage(),
            'count_page'   => $lists->lastPage(),
            'total'        => $lists->total(),
            'data'         => $lists->items(),
        ];
    }
    public function cashCreate($params)
    {
        $user_bank_id = $params['user_bank_id'];
        $score = $params['score'];
        $bank_info = UserBankModel::getInstance()->where(['id'=>$user_bank_id,'user_id'=>$this->user_id])->first();

        if (!$bank_info){
            $this->error='暂无数据';
            return false;
        }
        [$startOfMonth,$endOfMonth] = getThisMonth(date("Y-m",strtotime("-1 month")));
        $take = UserScoreModel::getInstance()->where(['user_id'=>$this->user_id])
            ->whereBetween('gift_time', [strtotime($startOfMonth), strtotime($endOfMonth)])->sum('score');

        $maxScore = sprintf('%.2f',$take);
        if($score>$maxScore) {
            $this->error='超出最大额度!';
            return false;
        }

        $user_info = UsersModel::getInstance()->user_info($this->user_id);
        $balance = $user_info['integral']; //19085.835

        $maxScore = sprintf('%.2f',$take);
        if($score>$balance) {
            $this->error='账户余额不足!';
            return false;
        }

        $integral = $balance - $score;
        $user_info['integral'] = $integral;
        $cash_insert = [
            'month'=>date("Y-m-01",strtotime("-1 month")),
            'user_id'=>$this->user_id,
            'user_bank_id'=>$user_bank_id,
            'real_name'=>$this->user_info['nickname']??"",
            'extract_type'=>'bank',
            'bank_code'=>$bank_info['number'],
            'balance'=>$balance,
            'extract_price'=>$score,//提现金额
            'status'=>0,
        ];
        DB::beginTransaction();
        try{
            UserExtractModel::getInstance()->create($cash_insert);
            UsersModel::getInstance()->where(['id'=>$this->user_id])->update(['integral'=>$integral]);
            parent::create($params); // TODO: Change the autogenerated stub
            DB::commit();
            $this->error='提交成功，等待审核和打款';
            return true;
        }catch (Exception $e){
            DB::rollBack();
            throw new Exception($e->getMessage());
        }
    }

}
